// 日志模块
const state = {
  // 日志列表
  logs: [],

  // 最大日志条数
  maxLogs: 50,

  // 日志过滤器
  logFilter: {
    type: 'all', // 'all', 'info', 'success', 'warning', 'error'
    keyword: ''
  }
}

const getters = {
  getLogs: state => state.logs,

  // 过滤后的日志
  getFilteredLogs: state => {
    let logs = state.logs

    // 类型过滤
    if (state.logFilter.type !== 'all') {
      logs = logs.filter(log => log.type === state.logFilter.type)
    }

    // 关键字过滤
    if (state.logFilter.keyword) {
      const keyword = state.logFilter.keyword.toLowerCase()
      logs = logs.filter(log =>
        log.message.toLowerCase().includes(keyword) ||
        (log.sourceCity && log.sourceCity.toLowerCase().includes(keyword)) ||
        (log.targetCity && log.targetCity.toLowerCase().includes(keyword))
      )
    }

    return logs
  },

  getLogFilter: state => state.logFilter,

  getLogCount: state => state.logs.length,

  // 按类型统计日志数量
  getLogStats: state => {
    const stats = {
      all: state.logs.length,
      info: 0,
      success: 0,
      warning: 0,
      error: 0
    }

    state.logs.forEach(log => {
      if (stats[log.type] !== undefined) {
        stats[log.type]++
      }
    })

    return stats
  },

  // 获取最新的几条日志
  getLatestLogs: (state) => (count = 10) => {
    return state.logs.slice(0, count)
  },

  // 获取特定类型的最新日志
  getLatestLogsByType: (state) => (type, count = 5) => {
    return state.logs
      .filter(log => log.type === type)
      .slice(0, count)
  }
}

const mutations = {
  // 添加日志
  ADD_LOG(state, log) {
    const logEntry = {
      id: Date.now() + Math.random(),
      timestamp: new Date().toISOString(),
      ...log
    }

    // 添加到日志列表开头
    state.logs.unshift(logEntry)

    // 限制最大日志数量
    if (state.logs.length > state.maxLogs) {
      state.logs = state.logs.slice(0, state.maxLogs)
    }

    // 缓存到本地存储
    try {
      localStorage.setItem('datav_logs', JSON.stringify(state.logs))
    } catch (error) {
      console.error('保存日志到本地存储失败:', error)
    }
  },

  // 清除所有日志
  CLEAR_LOGS(state) {
    state.logs = []
    try {
      localStorage.removeItem('datav_logs')
    } catch (error) {
      console.error('清除本地存储日志失败:', error)
    }
  },

  // 设置日志过滤器
  SET_LOG_FILTER(state, filter) {
    state.logFilter = { ...state.logFilter, ...filter }
  },

  // 从本地存储恢复日志
  RESTORE_LOGS_FROM_STORAGE(state) {
    try {
      const savedLogs = localStorage.getItem('datav_logs')
      if (savedLogs) {
        const logs = JSON.parse(savedLogs)
        // 只保留最近7天的日志
        const sevenDaysAgo = new Date()
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)

        state.logs = logs.filter(log => new Date(log.timestamp) > sevenDaysAgo)
      }
    } catch (error) {
      console.error('从本地存储恢复日志失败:', error)
    }
  },

  // 设置最大日志数量
  SET_MAX_LOGS(state, maxLogs) {
    state.maxLogs = maxLogs
    // 如果当前日志数量超过限制，截取
    if (state.logs.length > state.maxLogs) {
      state.logs = state.logs.slice(0, state.maxLogs)
    }
  }
}

const actions = {
  // 初始化日志模块
  initializeLogs({ commit }) {
    commit('RESTORE_LOGS_FROM_STORAGE')
    console.log('日志模块初始化完成')
  },

  // 添加日志
  addLog({ commit }, log) {
    commit('ADD_LOG', log)
  },

  // 添加信息日志
  addInfoLog({ dispatch }, message) {
    dispatch('addLog', {
      type: 'info',
      message,
      icon: 'info'
    })
  },

  // 添加成功日志
  addSuccessLog({ dispatch }, message) {
    dispatch('addLog', {
      type: 'success',
      message,
      icon: 'check'
    })
  },

  // 添加警告日志
  addWarningLog({ dispatch }, message) {
    dispatch('addLog', {
      type: 'warning',
      message,
      icon: 'warning'
    })
  },

  // 添加错误日志
  addErrorLog({ dispatch }, message) {
    dispatch('addLog', {
      type: 'error',
      message,
      icon: 'error'
    })
  },

  // 添加数据分流日志
  addFlowLog({ dispatch }, { message, sourceCity, targetCity, flowValue, status }) {
    dispatch('addLog', {
      type: status === 'start' ? 'info' : 'success',
      message,
      sourceCity,
      targetCity,
      flowValue,
      flowStatus: status,
      category: 'flow'
    })
  },

  // 清除所有日志
  clearAllLogs({ commit }) {
    commit('CLEAR_LOGS')
  },

  // 设置日志过滤器
  setLogFilter({ commit }, filter) {
    commit('SET_LOG_FILTER', filter)
  },

  // 设置最大日志数量
  setMaxLogs({ commit }, maxLogs) {
    commit('SET_MAX_LOGS', maxLogs)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
